import React, { useState, useEffect, useRef } from 'react';
import styles from './style.less';
import { Table, Space, Row, Col, Button, message } from 'antd';
import Footer from '@/components/Global/Footer';
import { ColumnsType } from 'antd/es/table';
import { AccountColumn, AccountList  } from './data';
import { getAccountList, saveAccount, auth, del, getAccount, updateAccount } from './service';
import { history } from 'umi';
import ModalComp from '@/components/Global/Modal/index';

// 登录按钮点击
const loginClick = (row: any) => {
  console.log(row);
  history.push({
    pathname: '/promotion/promotion_accounts/detail',
    query: {
      id: row.id,
      platformChannel: `${row.platformChannel}-${row.username}`,
      username: row.username
    }
  });
  return undefined;
}

const params = {};

export default function AccountsTable() {
  const [tableData, setTableData] = useState([]);
  const [page, setPage] = useState(1);
  const [modalFlag, setModalFlag] = useState(false);
  const btnRef = useRef<any>(null!);
  const [type, setType] = useState('');
  const [delText, setDelText] = useState('');
  const [delTitle, setDelTitle] = useState('');
  const [endText, setEndText] = useState('');
  const [endTitle, setEndTitle] = useState('');
  const [record, setRecord] = useState<AccountList>({})
  // const [formValue, setFormValue] = useState({});

  const getTable = () => {
    getAccountList(params).then(res => {
      console.log(res, '请求结果');
      if (res) {
        setTableData(res);
        // setPage(res.pageNum * 1);
        setPage(1);
        // setTableData([]);
      }
    });
  }

  const modalClick = (row: any, typeVal: string) => {
    console.log(row, typeVal);
    setType(typeVal);
    if (typeVal === 'del') {
      setDelTitle('确认删除此账号吗？');
      setDelText('删除账号后，此账号下所有数据全部清空，请确定操作!');
    } else if (typeVal === 'update') {
      const param = {
        id: row.id
      }
      getAccount(param).then(res => {
        console.log(res, '详情结果');
        if (res) {
          const form = btnRef.current.getForm();
          form.setFieldsValue(res);
          // setFormValue(res);
        }
      })
    }
    setRecord(row);
    setModalFlag(true);
  };

  const columns: ColumnsType<AccountColumn> = [
    {
      title: '平台',
      key: 'platformName',
      dataIndex: 'platformName',
      className: `${styles.content} ${styles.plan}`,
      // className: styles.content,
      // align: 'center'
    },
    {
      title: '业务',
      key: 'businessType',
      dataIndex: 'businessType',
      className: styles.content,
      // align: 'center'
    },
    {
      title: '账户名',
      key: 'username',
      dataIndex: 'username',
      className: styles.content,
      // align: 'center',
    },
    {
      title: '密码',
      key: 'password',
      dataIndex: 'password',
      className: styles.content,
      // align: 'center'
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      className: styles.content,
      // align: 'center',
      render: (text: string, row: any) => (
        <>{row.status === '0' ? '未授权' : '已授权'}</>
      )
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
      className: styles.content,
      // align: 'center'
    },
    {
      title: '创建者',
      key: 'createUser',
      dataIndex: 'createUser',
      className: styles.content,
      // align: 'center'
    },
    {
      title: '操作',
      // align: 'center',
      key: 'action',
      className: `${styles.content} ${styles.action}`,
      width: 350,
      render(row) {
        // console.log(row);
        let dom;
        if (row.status === '0') {
          dom = (
            <Space size="middle">
              <a onClick={() => { modalClick(row, 'empower') }}>授权</a>
              <a onClick={() => { modalClick(row, 'update') }}>编辑</a>
              <a onClick={() => { modalClick(row, 'del') }}>删除</a>
            </Space>
          );
        } else {
          dom = (
            <Space size="middle">
              <a onClick={() => { modalClick(row, 'unEmpower') }}>取消授权</a>
              <a onClick={() => { modalClick(row, 'update') }}>编辑</a>
              <a onClick={(() => loginClick(row))}>登录</a>
            </Space>
          );
        }
        return dom;
      }
    },
  ];

  // 新增编辑表单提交
  const onFinish = (values: any) => {
    console.log(values, '表单');
    if (type === 'addAccount') {
      // 新增的保存
      const param = { ...values, businessType: '代理运营' };
      saveAccount(param).then(res => {
        console.log(res, '新增账号结果');
        message.success('操作成功');
        setModalFlag(false);
        getTable();
      })
    } else {
      // 编辑保存
      const param = { ...values, id: record.id };
      updateAccount(param).then(res => {
        console.log(res, '修改账号结果');
        message.success('操作成功');
        setModalFlag(false);
        getTable();
      })
    }
  };

  // 其余弹窗确定
  const handleOk = () => {
    console.log(record, '其余弹窗确定')
    if (type === 'empower' && record.status === '0') {
      const param = {
        id: record.id,
        status: '1'
      }
      auth(param).then(res => {
        console.log(res, '授权结果');
        // message.success('授权成功！');
        // setModalFlag(false);
        // getTable();
        setType('interfaceEnd');
        setEndText('授权成功！');
        setEndTitle('');
        setModalFlag(true);
      })
    } else if (type === 'unEmpower' && record.status === '1') {
      const param = {
        id: record.id,
        status: '0'
      }
      auth(param).then(res => {
        console.log(res, '取消授权结果');
        // message.success('取消授权成功！');
        // setModalFlag(false);
        // getTable();
        setType('interfaceEnd');
        setEndText('取消授权成功！');
        setEndTitle('');
        setModalFlag(true);
      })
    } else if (type === 'del') {
      const param = {
        id: record.id * 1
      }
      del(param).then(res => {
        console.log(res, '删除账号结果');
        setType('interfaceEnd');
        setEndText('删除成功！');
        setEndTitle('');
        setModalFlag(true);
      })
    }
  };

  // 弹窗知道了按钮点击
  const sureClick = () => {
    setModalFlag(false);
    getTable();
  }

  useEffect(() => {
    getTable();
  }, []);

  return (
    <>
      <Row>
        <Col flex="auto">
          <Table<AccountColumn>
            dataSource={tableData}
            columns={columns}
            pagination={false}
            rowKey={(record) => record.id}
            // locale={{ emptyText: "空空如也呀~" }}
            scroll={{ y: 600 }}
          ></Table>
        </Col>
      </Row>
      <Footer
        footer={styles.footer}
        length={tableData.length}
        current={page}
        buttonGroup={
          <>
            <Button className={styles.addBtn} onClick={() => { modalClick('', 'addAccount') }}>
              添加账号
            </Button>
          </>
        }
      />
      <ModalComp
        modalFlag={modalFlag}
        setModalFlag={setModalFlag}
        type={type}
        width={400}
        ref={btnRef}
        onFinish={onFinish}
        delTitle={delTitle}
        delText={delText}
        endTitle={endTitle}
        endText={endText}
        handleOk={handleOk}
        sureClick={sureClick}
      />
      {/* propFormValue={formValue} */}
    </>
  );
}
